/*
 * @Author: CPS
 * @Date: 2020-07-14 11:52:19
 * @Last Modified by:   Administrator
 * @Last Modified time: 2020-08-04 16:56:41
 * @Projectname Electron-YYS
 * @Filename subWindows.js
 */
'use strict'
const {
  ipcMain,
  BrowserWindow
} = require('electron')


class subWindow {
  constructor(options) {
    console.log('子窗口初始化')
    this.win = null
    this.staic = false
    this.maxMsg = 3
    this.el = null
    this.channel = null

    this.defaultOptions = {
      templtae: '',
      width: 854,
      height: 480,
      frame: false, //无边框模式-无法移动
      autoHideMenuBar: true, //隐藏菜单栏
      transparent: true, //窗口透明
      resizable: false, //调整大小开关
      movable: false, //移动开关
      maximizable: false, //是否可以最大化
      // backgroundColor: '#48DDA9',
    }

    if (!options.template) return console.log('必须指定template html模板')
    if (options) Object.assign(this.defaultOptions, options)

    this.win = new BrowserWindow(this.defaultOptions)
    this.win.loadFile(options.template)
    console.log('loadFile win' + this.win.id)

    this.win //添加子窗口默认行为
      .once('ready-to-show', () => {
        this.show()
        // this.win.showInactive() //显示但不聚焦
        this.win.moveTop() //无论焦点如何, 将窗口移至顶端(z轴上的顺序).
      })
      .on('closed', () => {
        this.win = null
        this.close()
      })
      .on('window-all-closed', () => {
        this.win.quit()
        this.win = null
        this.close()
      })
  }

  show() {
    if (this.staic) {
      this.win.hiden()
    } else {
      // this.win.showInactive()
      this.win.show()
    }
  }

  close() {
    if (this.win) {
      this.win.close()
    }
    this.win = null
    this.staic = false
    this.el = null
    this.channel = null
    if (global.subWindow) global.subWindow = null
  }

  on(events, callback) {
    ipcMain.on(events, callback)
  }

  // 触发事件到子窗口
  send(event, data) {
    if (this.channel) {
      this.win.showInactive()
      this.win.moveTop()
      this.channel.reply(event, data)
    }
  }
}

console.log('loading sonWindows.js')

module.exports = (template, options) => {
  if (global.subWindow) return global.subWindow
  global.subWindow = new subWindow(template, options)
  return global.subWindow
}